<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules" hide-required-asterisk
           label-width="65px" @keydown.enter.native="submitForm">
    <el-form-item ref="username" prop="username">
      <el-input v-model="ruleForm.username" class="input" placeholder="请输入用户名 / 邮箱"
                type="text" @keydown.enter="submitForm"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="ruleForm.password" autocomplete="off" class="input"
                placeholder="请输入密码" show-password type="password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button class="input" type="primary" @click="submitForm">登录</el-button>
    </el-form-item>
    <a class="link" href="" @click="forgetPass">忘记密码？</a>
  </el-form>
</template>

<script>
import encrypt from '../mixin/encrypt'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Login',
  data() {
    // 还是校验一下登录的输入格式，免得输入格式不对还要请求后端
    const validate1 = (rule, value, callback) => {
      value = value.trim();
      if (value === '') {
        callback(new Error('用户名/邮箱不能为空'));
      } else {
        if (!value.includes('@')) {
          const reg = /^[\w\u4e00-\u9fa5]{6,12}$/;
          if (!reg.test(value)) {
            callback(new Error('用户名不存在'));
          } else callback();
        } else {
          const reg = /^[\w\u4e00-\u9fa5-]+@\w+\.+\w{2,}$/g;
          if (!reg.test(value)) {
            callback(new Error('请输入有效的邮箱地址'));
          } else callback();
        }
      }
    };
    const validate2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'));
      } else {
        const reg = /^\w{8,16}$/;
        if (!reg.test(value)) {
          callback(new Error('密码错误'));
        } else callback();
      }
    }
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [{ validator: validate1, trigger: 'none' }],
        password: [{ validator: validate2, trigger: 'none' }],
      },
    };
  },
  mixins: [encrypt],
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
        //  先检查本地是否有公钥存在
          try {
            const encrypted = await this.encrypt(this.ruleForm.password);
            try {
              const res = await this.$axios.post(this.$store.state.serverUrl + '/api/login',
                  { username:this.ruleForm.username.trim(), inputPass:encrypted });
              if (res.data['status'] === 0) {
                const {token, username, friends, messages} = res.data['msg'];
                this.$store.state.username = username;
                if (friends) this.$store.state.friendList = friends.split(';');
                if (messages) this.$store.state.messages = JSON.parse(messages);
                this.$store.state.isFormDialogVis = false;
                localStorage.setItem('token', token);
                this.$store.commit('updateToken');
                this.$message.success('登录成功！')
              } else {
                if (res.data['status'] === 1) {
                  this.$refs.username.error = res.data['msg'];
                } else {
                  await this.$alert('请检查用户名或密码是否正确', '登录失败')
                }
              }
            } catch (err) {
              await this.$alert(err.message, '网络连接出错')
            }
          } catch (err) {
            await this.$alert(err.message, '加密失败');
          }
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    forgetPass(e) {
      e.preventDefault();
      this.$emit('forgetPass')
    }
  },
  mounted() {
    this.$bus.$on('clearLogValRes', () => this.$refs.ruleForm.clearValidate());
    this.$bus.$on('resetLogForm', () => this.resetForm());
  },
  beforeDestroy() {
    this.$bus.$off('clearLogValRes');
    this.$bus.$off('resetLogForm', () => this.resetForm());
  }
}
</script>

<style lang="scss" scoped>
  .input {
    width: 80%;
    margin-top: 3%;
  }
  .link {
    position: relative;
    left: 75%;
    &:link {
      color: gray;
    }
    &:visited {
      color: gray;
    }
    &:hover {
      color: dodgerblue;
    }
  }
</style>